package com.itfreer.file.path;

import java.io.File;
import java.io.FileInputStream;
import java.io.RandomAccessFile;

import com.itfreer.file.FileSegmentInfo;

/**
 * 定义对象下载接口
 */
public class FileDownload extends BasePath {

	/**
	 * 单一实例
	 */
	public static final FileDownload instance = new FileDownload();

	private FileDownload(){

	}

	/**
	 * 获取对象
	 * 
	 * @param bucketName
	 *            存储块名称
	 * @param objectKey
	 *            对象名称主键
	 */
	public byte[] getObject(String bucketName, String objectKey) {
		String path = getBasePath();
		if (path.endsWith("/")) {
			path += bucketName + "/";
		} else {
			path += "/" + bucketName + "/";
		}
		String filePath = path + objectKey;
		File fileInfo = new File(filePath);
		if (fileInfo.exists()) {
			try {
				FileInputStream in = new FileInputStream(fileInfo);
				byte[] buffer = new byte[in.available()];
				in.read(buffer);
				in.close();
				return buffer;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		} else {
			return null;
		}
	}

	/**
	 * 断点续传下载
	 * 
	 * @param bucketName
	 *            存储块名称
	 * @param objectKey
	 *            对象存储key
	 * @param segmentInfo
	 *            分段信息
	 */
	public FileSegmentInfo downloadFile(String bucketName, String objectKey, FileSegmentInfo segmentInfo) {
		String path = getBasePath();
		if (path.endsWith("/")) {
			path += bucketName + "/";
		} else {
			path += "/" + bucketName + "/";
		}
		String filePath = path + objectKey;
		File fileInfo = new File(filePath);

		// 计算文件块总数
		FileSegmentInfo fileSegmentInfo = (FileSegmentInfo) segmentInfo.clone();
		fileSegmentInfo.setFileLength(fileInfo.length());

		if (fileInfo.exists()) {
			try {
				RandomAccessFile randomAccessFile = new RandomAccessFile(fileInfo, "r");
				randomAccessFile.seek(fileSegmentInfo.getSegmentIndex() * fileSegmentInfo.getSegmentSize());
				byte[] buffer = null;

				if (fileSegmentInfo.isLastSegment()) {
					int lastLength = (int) (randomAccessFile.length()
							- fileSegmentInfo.getSegmentIndex() * fileSegmentInfo.getSegmentSize());
					buffer = new byte[lastLength];
					randomAccessFile.read(buffer, 0, lastLength);
					fileSegmentInfo.setSegmentContent(buffer);
				} else {
					buffer = new byte[fileSegmentInfo.getSegmentSize()];
					randomAccessFile.read(buffer, 0, fileSegmentInfo.getSegmentSize());
					fileSegmentInfo.setSegmentContent(buffer);
				}
				randomAccessFile.close();
				return fileSegmentInfo;
			} catch (Exception e) {
				e.printStackTrace();
				return null;
			}
		} else {
			return null;
		}
	}
}